const api = require('../../api/api.js');
const util = require('../../utils/util.js');
const app = getApp();

Page({
  data: {
    enterprise: {},
    entId: 0,
    enterprise_copy: {},
    isDisabled: true,
    region: [],
    region_copy: [],
    images: [],
    images_copy: [],
    imgUrl: app.globalData.imgUrl + 'enterpriseImage/',
    tip: '',
    icon: '/imgs/icon_edit.png',
    delImgs: [],
    addImgs: [],
    localImgSrc: '',
    localImgSrc_copy: ''
  },
  onLoad(o) {
    let that = this;
    let entId = o.entId; 
    api.queryEnterpriseInfo({
      data: {
        entId
      },
      success(res) {
        console.log(res.data);
        let enterprise = res.data.enterprise;
        let region = [enterprise.province, enterprise.city, enterprise.county];
        let imgUrl = that.data.imgUrl;
        if (enterprise.image === '') {
          var localImgSrc = imgUrl + 'defaultLogo.png';
        } else {
          var localImgSrc = imgUrl + enterprise.image;
        }
        if (res.data.imageSize === 9) {
          var tip = '(最多九张)';
        } else {
          var images = res.data.enterpriseImage;
          images = images.map(i => {
            return {
              imgUrl: imgUrl + i.image,
              imgID: i.id
            }
          });
        }
        that.setData({
          enterprise,
          entId,
          region,
          localImgSrc,
          images
        });
        util.getLocalStorage(['userId'], that);
      }
    });
  },
  edit() {
    let that = this;
    let isDisabled = !that.data.isDisabled;
    let icon;
    let tip = '';
    if (isDisabled === true) {
      wx.showModal({
        title: '提示',
        content: '取消编辑？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_edit.png';
            if (that.data.images_copy.length === 9) {
              tip = '(最多九张)';
            }
            that.setData({
              tip: tip,
              enterprise: that.data.enterprise_copy,
              region: that.data.region_copy,
              localImgSrc: that.data.localImgSrc_copy,
              images: that.data.images_copy.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '编辑资料？',
        success(res) {
          if (res.confirm) {
            icon = '/imgs/icon_cancel.png';
            that.setData({
              enterprise_copy: that.data.enterprise,
              region_copy: that.data.region,
              localImgSrc_copy: that.data.localImgSrc,
              images_copy: that.data.images.concat(),
              isDisabled: isDisabled,
              icon: icon
            });
          }
        }
      })
    }
  },
  delimg(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let images = this.data.images;
    let addImgs = this.data.addImgs;
    let img = images[index];
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success(e) {
        if (e.confirm) {
          images.splice(index, 1);
          if (img.imgID === -1) {
            for (let i = 0; i < addImgs.length; i++) {
              if (img.imgUrl === addImgs[i]) {
                addImgs.splice(i, 1);
              }
            }
          } else {
            that.data.delImgs.push(img.imgID);
          }
          that.setData({
            images: images,
            tip: ''
          });
        }
      }
    })
  },
  addimg() {
    let that = this;
    let images = this.data.images;
    let tip = '';
    wx.chooseImage({
      count: 9 - images.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        let tempFilePaths = res.tempFilePaths;
        that.data.addImgs.push(...tempFilePaths);
        tempFilePaths = tempFilePaths.map((i) => {
          return {
            imgUrl: i,
            imgID: -1
          }
        });
        images.push(...tempFilePaths);
        if (images.length === 9) {
          tip = '(最多九张)';
        }
        that.setData({
          images: images,
          tip: tip
        });
      }
    })
  },
  delImage(count) {
    let that = this;
    let imgs = this.data.delImgs;
    let len = imgs.length;
    let id = imgs[count];
    console.log(id);
    if (count === len) {
      return;
    }
    api.delEnterpriseImage({
      data: {
        id
      },
      success(res) {
        that.delImage(++count);
      }
    });
  },
  addImage(count) {
    let that = this;
    let imgs = this.data.addImgs;
    let len = imgs.length;
    let img = imgs[count];
    let entId = this.data.entId;
    if (count === len) {
      return;
    }
    wx.getStorage({
      key: 'userId',
      success(res) {
        let userId = res.data;
        api.addFile({
          data: {
            userId: userId,
            path: 'enterpriseImage',
            filePath: img
          },
          success(res) {
            let image = JSON.parse(res.data).fileName;
            api.addEnetrpriseImage({
              data: {
                image,
                entId
              },
              success(res) {
                that.addImage(++count);
              }
            });
          }
        });
      }
    })
  },
  formSubmit(e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定修改吗？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '正在修改'
          })
          let userId = that.data.userId;
          let entId = that.data.entId;
          let name = e.detail.value.name.trim();
          let province = that.data.region[0];
          let city = that.data.region[1];
          let county = that.data.region[2];
          let address = e.detail.value.address.trim();
          let img = that.data.localImgSrc;
          let changeImg = that.data.localImgSrc === that.data.localImgSrc_copy;
          let image = '';
          if (changeImg) { //如果logo图片没有改变
            image = 'no';
            updateEnterprise();
          } else { //如果logo图片改变
            api.addFile({
              data: {
                userId: userId,
                path: 'enterpriseImage',
                filePath: img
              },
              success(res) {
                image = JSON.parse(res.data).fileName;
                updateEnterprise();
              }
            });
          }

          function updateEnterprise() {
            api.updateEnterprise({
              data: {
                entId,
                entName: name,
                province,
                city,
                county,
                location: address,
                image
              },
              success(res) {
                wx.hideLoading();
                wx.showToast({
                  title: '修改成功！',
                  icon: 'none'
                });
                that.addImage(0);
                that.delImage(0);
                let pages = getCurrentPages();
                pages[pages.length - 2].onLoad();
                wx.navigateBack({
                  delta: -1
                });
              }
            });
          }
        }
      }
    })
  },
  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  // logo图片选择
  changeImg(e) {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          localImgSrc: res.tempFilePaths[0]
        });
      }
    })
  }
})